﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsMobile.Samples.Location;

namespace Home.MobileSales.WorkGps
{
    public class GpsWorker
    {
        private static GpsWorker _instance = null;
        private GpsPosition _position = null;
        private Gps gps = new Gps();
        private GPSData _gpsData = new GPSData();

        public void StartGps ()
        {
            
            if (!gps.Opened)
            {
                gps.LocationChanged += gps_LocationChanged;
                gps.Open();
            }
        }

        public void StopGps()
        {
            if (gps.Opened)
            {
                gps.Close();
            }
        }

        private void gps_LocationChanged(object sender, LocationChangedEventArgs args)
        {
            _position = args.Position;
            BuildData();
        }

        private void BuildData ()
        {
            if (gps.Opened)
            {
                if (_position != null)
                {
                    if (_position.LatitudeValid && _position.LongitudeValid && _position.TimeValid)
                    {
                        GPSData gpsData = new GPSData();
                        gpsData.lat = _position.LatitudeInDegreesMinutesSeconds.ToString();
                        gpsData.lon = _position.LongitudeInDegreesMinutesSeconds.ToString();
                        gpsData.date = _position.Time;
                        _gpsData = gpsData;
                    }
                }
            }
        }
        
        public GPSData GpsData
        {
            get { return _gpsData; }
        }

        public static GpsWorker GetInstance ()
        {
            return _instance ?? (_instance = new GpsWorker());
            
        }
    }
}
